<script lang="ts" setup>
import { FormContext } from 'blitzar'
import { markRaw, onMounted } from 'vue'
import CAdminTable from '../CAdminTable.vue'
import { SortState, TableInfo } from '../tableInfo'
import { Payment, Invoice, dbPayments, dbInvoices } from './helpers/dbPaymentsAndInvoices'
import { InvoiceState, PaymentState } from './helpers/dbPaymentsAndInvoices'

const schema = [
  {
    id: 'date',
    label: 'date',
    parseValue: (_date: undefined, context: FormContext) => {
      const { paymentDate, invoiceDate } = context.formData
      return paymentDate || invoiceDate
    },
    sortable: false,
  },
  {
    id: 'state',
    label: 'state',
    parseValue: (state: PaymentState | InvoiceState) => {
      if (state === 'default' || state === 'request') return '入金'
      return '請求'
    },
    sortable: false,
  },
  { id: 'id', label: 'id', sortable: false },
  { id: 'companyId', label: 'companyId', sortable: false },
  { id: 'name', label: 'name', sortable: false },
]

const tableInfo: TableInfo<Payment | Invoice> = {
  schemaColumns: schema,
  db: [dbInvoices, dbPayments],
}

onMounted(() => {
  const target = document.querySelector('.admin-table')?.parentNode ?? null

  // @ts-ignore
  if (target) target.style.width = '860px'
})

const sortState: SortState = [
  {
    id: '_date',
    direction: 'desc',
    parseValue: (_date: undefined, context) => {
      const { paymentDate, invoiceDate } = context.formData
      return paymentDate || invoiceDate
    },
  },
  {
    id: 'state',
    direction: 'asc',
    parseValue: (state: PaymentState | InvoiceState) => {
      if (state === 'default' || state === 'request') return 1
      return 2
    },
  },
  {
    id: 'id',
    direction: 'desc',
    parseValue: (id: string) => {
      return id.split('-').slice(1).join('-')
    },
  },
]
</script>

<template>
  <CAdminTable
    :P_SortState="sortState"
    :tableInfo="tableInfo"
    :p_Addable="true"
    p_Title="タイトル漢字english"
    p_TableType="mini"
    p_EditType="row-click"
  />
</template>
